package com.zql;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/*
  @Classname JDBCExecute
  @Description 直接通过jdbc查询数据库的代码
  @Date 2021/7/30 10:43
  @Created by zhangql
 */
public class JDBCExecute {
    public static List<User> getQueryList() throws SQLException {
        Connection connection = null;

        ArrayList<User> list = new ArrayList<>();
        User user = new User();

        try {
            //加载数据库驱动
            Class<?> aClass = Class.forName("com.mysql.jdbc.Driver");
            //获取数据库连接
            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/my-mybatis?useUnicode=true&amp;characterEncoding=utf8&" +
                    "user=root&password=123456");

            String sql = "select  * from user where id=?";
            //获取预处理prepareStatement
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setInt(1, 1);
            //查询数据库并获取查询结果
            ResultSet resultSet = preparedStatement.executeQuery();
            while (resultSet.next()) {
                int id = resultSet.getInt("id");
                String userName = resultSet.getString("userName");
                String password = resultSet.getString("password");
                String birthday = resultSet.getString("birthday");
                user.setBirthday(birthday);
                user.setUserNmae(userName);
                user.setId(id);
                user.setPassword(password);
                list.add(user);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            connection.close();
        }

        return list;
    }

    public static void main(String[] args) throws SQLException {
        List<User> userList = JDBCExecute.getQueryList();
        userList.forEach(user -> System.out.println(user.toString()));
    }
}